<!-- 本示例未包含完整css，获取外链css请参考上文，在hello uni-app项目中查看 -->
<template>
	<div style="background: black;width: 100%;height: 100vh;">
		<movable-area scale-area class="movable-area" v-if="imageSrc" :style="{ top: areaTop+'px',width:CLIP_WIDTH_RPX+'rpx',height:CLIP_HEIGHT_RPX+'rpx',left:(750 - CLIP_WIDTH_RPX) / 2+'rpx'}">
			<movable-view scale inertia damping="1000" direction="all" scale-min="1" :style="{width: initialWidth+'px',height:initialHeight+'px'}"
			 :x="initialX" :y="initialY" @change="onChange" @scale="onScale">
				<image class="image" :src="imageSrc" />
			</movable-view>
		</movable-area>


		<view class="clip-box" :style="{ top: areaTop+'px',width:CLIP_WIDTH_RPX+'rpx',height:CLIP_HEIGHT_RPX+'rpx',left:(750 - CLIP_WIDTH_RPX) / 2+'rpx'}" />
		<view class="bottom-btns">
			<view class="bottom-item" @click="setActive(2)">
				<image src="../../../static/img/34.png" style="width: 50rpx;height: 60rpx;" v-if="active != 2" @click="setActive(2)"></image>
				<image src="../../../static/img/34c.png" style="width: 50rpx;height: 60rpx;" v-if="active == 2" @click="setActive(2)"></image>
				<span :style="active == 2?'color: #F6CE46;':''" @click="setActive(2)">3:4</span>
			</view>
			<view class="bottom-item" @click="setActive(3)">
				<image src="../../../static/img/43.png" style="width: 60rpx;height: 50rpx;" v-if="active != 3" @click="setActive(3)"></image>
				<image src="../../../static/img/43c.png" style="width: 60rpx;height: 50rpx;" v-if="active == 3" @click="setActive(3)"></image>
				<span :style="active == 3?'color: #F6CE46;':''" @click="setActive(3)">4:3</span>
			</view>
			<view class="bottom-item" @click="setActive(4)">
				<image src="../../../static/img/11.png" style="width: 60rpx;height: 60rpx;" v-if="active != 4" @click="setActive(4)"></image>
				<image src="../../../static/img/11c.png" style="width: 60rpx;height: 60rpx;" v-if="active == 4" @click="setActive(4)"></image>
				<span :style="active == 4?'color: #F6CE46;':''" @click="setActive(4)">1:1</span>
			</view>
			<view class="bottom-item">
				<view @tap="onClickConfirm">下一步</view>
			</view>
		</view>
		<canvas v-if="canvasWidth" canvas-id="shareCardCanvas" type="2d" class="canvas" :style="{width: canvasWidth+'px',height:canvasHeight+'px'}"></canvas>
	</div>
</template>

<script>
	import {
		loadCanvasImage
	} from './util'
	export default {
		data() {
			return {
				active: 2,
				CLIP_WIDTH_RPX: 750,
				CLIP_HEIGHT_RPX: 850,
				dpr: 2,
				// 用户选择的图片的地址
				imageSrc: '',
				// movable-area top 的值
				areaTop: 0,
				initialWidth: 0,
				initialHeight: 0,
				initialX: 0,
				initialY: 0,
				initialScale: 1,
				clipWidth: 0,
				clipHeight: 0,
				x: 0,
				y: 0,
				scale: 1,
				// 存下这两个值是因为在 wxml 中有用到，来设置 canvas 宽高了
				canvasWidth: 0,
				canvasHeight: 0,
				imgSrc: undefined,
				urlIndex: 0,
				// imgList: [],
				NewImgList: [],
				dataList: {},
				uploadList: [],
				imgFlieListOld: []
			}
		},
		onLoad(options) {
			this.urlIndex = 0
			if(options.dataList){
				this.dataList = JSON.parse(options.dataList)
				this.uploadList = this.dataList.imgFlieList.split(',')
				console.log('触发了呀0	')
				if(this.dataList.imgFlieListOld){
					this.imgFlieListOld = this.dataList.imgFlieListOld.split(',')
					console.log('触发了呀1')
					if(this.imgFlieListOld.length > 0){
						console.log('触发了呀')
						let imgList = this.imgFlieListOld.join()+','+this.uploadList.join();
						this.uploadList = imgList.split(',')
						this.uploadList = Array.from(new Set(this.uploadList))
						console.log('this.uploadList:')
						console.log(this.uploadList)
						this.urlIndex = this.urlIndex + this.imgFlieListOld.length
						this.getImgDetails(this.uploadList[this.urlIndex])
						return false
					}
				}else{
					this.getImgDetails(this.uploadList[this.urlIndex])
				}
			}
		},
		watch:{
			urlIndex(){
				if(this.imgFlieListOld.length > 0){
					if((this.uploadList.length-1) > this.NewImgList.length){
						this.getImgDetails(this.uploadList[this.urlIndex])
					}else{
						let data = this.dataList
						this.NewImgList = this.imgFlieListOld.join()+','+this.NewImgList.join();
						this.NewImgList = this.NewImgList.split(',')
						data.imgFlieList = this.NewImgList.toString()
						data = JSON.stringify(this.dataList)
						uni.redirectTo({
							url: '../PublishedDiary/PublishedDiary?type='+1+'&dataList='+data
						})
					}
				}else{
					if(this.uploadList.length > this.NewImgList.length){
						this.getImgDetails(this.uploadList[this.urlIndex])
					}else{
						let data = this.dataList
						data.imgFlieList = this.NewImgList.toString()
						data = JSON.stringify(this.dataList)
						uni.redirectTo({
							url: '../PublishedDiary/PublishedDiary?type='+1+'&dataList='+data
						})
					}
				}
				
				
			}
		},
		methods: {
			getImgDetails(e){  //重新计算图片大小展示页面
				let that = this
				that.imgSrc = e
				console.log('第一张为：'+e)
				const imageSrc = e
				const {
					windowWidth,
					windowHeight,
					pixelRatio
				} = wx.getSystemInfoSync()
				// 裁剪框配置值是 rpx ，计算出对应的 px 值
				const clipWidth = (windowWidth / 750) * that.CLIP_WIDTH_RPX
				const clipHeight = (windowWidth / 750) * that.CLIP_HEIGHT_RPX
				// 计算出裁剪框应该距离顶部的值，以便定位
				const areaTop = (windowHeight - clipHeight) / 2    //距离截图框距离顶部的高度
				wx.getImageInfo({
					src: imageSrc,
					success: (res) => {
						const {
							width,
							height
						} = res
						// 在知道图片本身的宽高后，一开始需要缩放一下图片使得图片的宽或者高等于裁剪框尺寸
						const scale = Math.max(clipWidth / width, clipHeight / height)
						const initialWidth = width * scale
						const initialHeight = height * scale
						// that.dpr = pixelRatio,
						that.imageSrc = imageSrc,
						that.areaTop = areaTop,
						that.initialWidth = initialWidth,
						that.initialHeight = initialHeight,
						that.initialX = (clipWidth - initialWidth) / 2,
						that.initialY = (clipHeight - initialHeight) / 2,
						that.x = (clipWidth - initialWidth) / 2,
						that.y = (clipHeight - initialHeight) / 2,
						that.initialScale = scale,
						that.clipWidth = clipWidth,
						that.clipHeight = clipHeight
					},
				})
			},
			setActive(e){
				this.active = e
				switch(e){
					case 2:
						this.CLIP_WIDTH_RPX = 750
						this.CLIP_HEIGHT_RPX = 850
						// this.canvasWidth = 750
						// this.canvasHeight = 850
						break;
					case 3:
						this.CLIP_WIDTH_RPX = 750
						this.CLIP_HEIGHT_RPX = 650
						// this.canvasWidth = 750
						// this.canvasHeight = 650
						break;
					case 4:
						this.CLIP_WIDTH_RPX = 750
						this.CLIP_HEIGHT_RPX = 750
						// this.canvasWidth = 750
						// this.canvasHeight = 750
						break;
				}
				let that = this
				const imageSrc = that.imgSrc
				const {
					windowWidth,
					windowHeight,
					pixelRatio
				} = wx.getSystemInfoSync()
				// 裁剪框配置值是 rpx ，计算出对应的 px 值
				const clipWidth = (windowWidth / 750) * that.CLIP_WIDTH_RPX
				const clipHeight = (windowWidth / 750) * that.CLIP_HEIGHT_RPX
				// 计算出裁剪框应该距离顶部的值，以便定位
				const areaTop = (windowHeight - clipHeight) / 2    //距离截图框距离顶部的高度
				wx.getImageInfo({
					src: imageSrc,
					success: (res) => {
						const {
							width,
							height
						} = res
						// 在知道图片本身的宽高后，一开始需要缩放一下图片使得图片的宽或者高等于裁剪框尺寸
						const scale = Math.max(clipWidth / width, clipHeight / height)
						const initialWidth = width * scale
						const initialHeight = height * scale
						// that.dpr = pixelRatio,
						that.imageSrc = imageSrc,
						that.areaTop = areaTop,
						that.initialWidth = initialWidth,
						that.initialHeight = initialHeight,
						that.initialX = (clipWidth - initialWidth) / 2,
						that.initialY = (clipHeight - initialHeight) / 2,
						that.x = (clipWidth - initialWidth) / 2,
						that.y = (clipHeight - initialHeight) / 2,
						that.initialScale = scale,
						that.clipWidth = clipWidth,
						that.clipHeight = clipHeight
					},
				})
			},
			onChange(e) {
				const {
					x,
					y
				} = e.detail
				this.x = x
				this.y = y
			},
			onScale(e) {
				const {
					x,
					y,
					scale
				} = e.detail
				this.x = x
				this.y = y
			},
			onClickCancel: function(e) {
				wx.navigateBack()
			},

			onClickConfirm: function(e) {
				if(this.imgFlieListOld.length > 0){
					if((this.uploadList.length-1) > this.NewImgList.length){
						uni.showLoading({
							title: '裁剪中...',
							mask: true
						})
						const {
							dpr,
							imageSrc,
							x,
							y,
							initialScale,
							scale,
							clipWidth,
							clipHeight,
						} = this
						const totalScale = scale * initialScale
						const sx = -x / totalScale
						const sy = -y / totalScale
						const canvasWidth = clipWidth / totalScale
						const canvasHeight = clipHeight / totalScale

						this.canvasWidth = canvasWidth
						this.canvasHeight = canvasHeight
						const query = uni.createSelectorQuery()
						let self = this
						setTimeout(function() {
							query.select('.canvas').fields({
								node: true,
								size: true
							})
							query.exec((res) => {
								const canvas = res[0].node
								const context = canvas.getContext('2d')
								canvas.width = res[0].width * dpr
								canvas.height = res[0].height * dpr
								context.scale(dpr, dpr)
								// 在 canvas 上把原图上裁剪框对应的部分给画上去，然后导出即可
								loadCanvasImage(canvas, imageSrc).then((img) => {
									context.drawImage(
										img,
										sx,
										sy,
										canvasWidth,
										canvasHeight,
										0,
										0,
										canvasWidth,
										canvasHeight
									)
									wx.canvasToTempFilePath({
										fileType: 'jpg',
										canvas,
										success: (res) => {
											self.NewImgList.push(res.tempFilePath)
											self.urlIndex += 1
											uni.hideLoading()
											return false
										},
										fail(e) {
											uni.hideLoading()
										},
									})
								})
							})
						}, 1000)
					}else{
						let data = this.dataList
						this.NewImgList = this.imgFlieListOld.join()+','+this.NewImgList.join();
						this.NewImgList = this.NewImgList.split(',')
						data.imgFlieList = this.NewImgList.toString()
						data = JSON.stringify(this.dataList)
						uni.redirectTo({
							url: '../PublishedDiary/PublishedDiary?type='+1+'&dataList='+data
						})
					}
				}else{
					if(this.uploadList.length > this.NewImgList.length){
					// if(this.uploadList.length > this.NewImgList.length){
						uni.showLoading({
							title: '裁剪中...',
							mask: true
						})
						const {
							dpr,
							imageSrc,
							x,
							y,
							initialScale,
							scale,
							clipWidth,
							clipHeight,
						} = this
						const totalScale = scale * initialScale
						const sx = -x / totalScale
						const sy = -y / totalScale
						const canvasWidth = clipWidth / totalScale
						const canvasHeight = clipHeight / totalScale
				
						this.canvasWidth = canvasWidth
						this.canvasHeight = canvasHeight
						const query = uni.createSelectorQuery()
						let self = this
						setTimeout(function() {
							query.select('.canvas').fields({
								node: true,
								size: true
							})
							query.exec((res) => {
								const canvas = res[0].node
								const context = canvas.getContext('2d')
								canvas.width = res[0].width * dpr
								canvas.height = res[0].height * dpr
								context.scale(dpr, dpr)
								// 在 canvas 上把原图上裁剪框对应的部分给画上去，然后导出即可
								loadCanvasImage(canvas, imageSrc).then((img) => {
									context.drawImage(
										img,
										sx,
										sy,
										canvasWidth,
										canvasHeight,
										0,
										0,
										canvasWidth,
										canvasHeight
									)
									wx.canvasToTempFilePath({
										fileType: 'jpg',
										canvas,
										success: (res) => {
											self.NewImgList.push(res.tempFilePath)
											self.urlIndex += 1
											uni.hideLoading()
											return false
										},
										fail(e) {
											uni.hideLoading()
										},
									})
								})
							})
						}, 1000)
					}else{
						let data = this.dataList
						data.imgFlieList = this.NewImgList.toString()
						data = JSON.stringify(this.dataList)
						uni.redirectTo({
							url: '../PublishedDiary/PublishedDiary?type='+1+'&dataList='+data
						})
					}
				}
			},
		}
	}
</script>
<style scoped lang="scss">
	.bottom-item{
		width: 15%;
		height: 80%;
		display: flex;
		background: black;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		font-size: 28rpx;
		color: white;
		image{
			width: 100%;
			height: 70%;
			display: flex;
			justify-content: center;
		}
		span{
			width: 100%;
			height: 30%;
			display: flex;
			align-items: center;
			justify-content: center;
			// margin-top: 15rpx;
		}
		view{
			width: 100%;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #F6CE46;
			border-radius: 15rpx;
		}
	}
	page {
	  /* 不加这句页面会上下左右可以滚动 */
	  overflow: hidden;
	}
	
	.clip-box {
	  box-sizing: border-box;
	  position: absolute;
	  border: 2px solid #F6CE46;
	  pointer-events: none;
	}
	
	.image {
	  /* 这里这样写样式是因为不这样写在 ios 下图片会糊 */
	  /* 详见 https://developers.weixin.qq.com/community/develop/doc/000cca893107c8895fc839e6351400 */
	  width: 400%;
	  height: 400%;
	  transform: translate3d(0, 0, 0) scale(0.25, 0.25);
	  transform-origin: left top;
	}
	
	.bottom-btns {
	  position: fixed;
	  bottom: 0;
	  padding-bottom: 10px;
	  width: 750rpx;
	  display: flex;
	  align-items: center;
	  justify-content: space-around;
	  background: black;
	  height: 160rpx;
	}
	
	/* 把 canvas 定位到屏幕之外 */
	.canvas {
	  position: fixed;
	  left: 100%;
	  top: 100%;
	}
	
</style>
